﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Services;

/// <summary>
/// Summary description for chatProg
/// </summary>
[WebService(Namespace = "http://www.spoiledtechie.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class chatProg : System.Web.Services.WebService
{
    public chatProg()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    /// <summary>
    /// gets the messages of the current users.
    /// </summary>
    /// <param name="sender">the sender of the messages</param>
    /// <param name="recipient">the recipient of the messages</param>
    /// <param name="lastUid">the last id of the last message retrieved.</param>
    /// <returns>returns any formatted messages.</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getMessages(string sender, string recipient, string lastUid)
    {
        IM.deleteMessages(sender);//Deletes any messages awaiting.
        return IM.getChatMessages(sender, recipient, lastUid);
    }
    /// <summary>
    /// inserts the typed messages into the system.
    /// </summary>
    /// <param name="message">the messaged</param>
    /// <param name="sender">the sender of the message</param>
    /// <param name="recipient">The recipient of the message</param>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public void setMessage(string message, string sender, string recipient)
    {
        message = message.Replace("<p>", "").Replace("</p>", "");//strips the formatteded paragraphs in the html so that it doesn't mess up the message.
        IM.ChatInsertMessages(message, recipient, sender); //inserts the message.
        IM.setChatMessagesWaiting(sender, recipient);//Inserts a notification that a message is waiting.
    }
    /// <summary>
    /// Gets any group messages that have been entered.
    /// </summary>
    /// <param name="sender">the sender of the message</param>
    /// <param name="recipient">the receiver of the message in which this is the Group name.</param>
    /// <param name="lastUid">the id of the last message recieved.</param>
    /// <returns>returns the formmated messages.</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getGroupMessages(string sender, string recipient, string lastUid)
    {
        IM.setChatRoomTime(recipient);//resets the room time.
        IM.RemoveOldGroups();//removes any old groups that have time expired.
        return IM.getGroupChatMessages(sender, recipient, lastUid);//gets the group chat messages.
    }
    /// <summary>
    /// Removes the old groups as times has expired for any non used groups.
    /// </summary>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public void removeOldGroups()
    {
        IM.RemoveOldGroups();
    }
    /// <summary>
    /// inserts a group messaged.
    /// </summary>
    /// <param name="message">the message to insert</param>
    /// <param name="sender">the sender of the message</param>
    /// <param name="recipient">the reciever of the message.</param>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public void setGroupMessage(string message, string sender, string recipient)
    {
        message = message.Replace("<p>", "").Replace("</p>", "");//strips out the paragraph text.
        IM.ChatGroupInsertMessages(message, recipient, sender);//inserts the message.
    }
    /// <summary>
    /// This is a keep alive to keep the session alive as long as the user is logged in.
    /// </summary>
    /// <returns>string (1:worked 2:problem 3:not authenticated, checks if any messages have been stored for the users, returns the domain path for the app)</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] keepListAlive()
    {
        string[] validation = new string[4];
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            try
            {
                MembershipUser mu = Membership.GetUser();
                mu.LastActivityDate = DateTime.UtcNow;
                Membership.UpdateUser(mu);
                validation[0] = "1";
                validation[1] = IM.checkMessages();
                validation[2] = IM.Server_Port_Secure();
                return validation;
            }
            catch
            {
                validation[0] = "2";
                return validation;
            }
        }
        validation[0] = "0";
        return validation;
    }
    /// <summary>
    /// Adds a room to the list.
    /// </summary>
    /// <param name="roomName"></param>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public void addToRooms(string roomName)
    {
        IM.addRooms(roomName);
    }
    /// <summary>
    /// gets any rooms in the list for the list boxes that display the active groups.
    /// </summary>
    /// <returns></returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getRooms()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var getList = (from cr in db.IM_Chat_Rooms
                       select cr.room_name).Distinct();

        string[] items = new string[getList.Count()];
        int i = 0;
        foreach (string item in getList)
        {
            items[i] = item;
            i++;
        }
        return items;
    }
    /// <summary>
    /// gets the users of the room id
    /// </summary>
    /// <param name="roomID">this is a Guid for the room ID but passed as a string.</param>
    /// <returns>returns a string of the users in the group.</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getUsers(string roomID)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var getUsers = (from cr in db.IM_Chat_Rooms
                        where cr.room_ID == new Guid(roomID)
                        select cr.userinRoom).Distinct();

        string[] items = new string[getUsers.Count()];
        int i = 0;
        foreach (Guid item in getUsers)
        {
            items[i] = IM.UserName(item);
            i++;
        }
        return items;
    }
    /// <summary>
    /// gets the users that are online
    /// </summary>
    /// <returns>a string of all the users.</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getUsersOnline()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var getUsersOnline = (from au in db.aspnet_Users
                              where au.LastActivityDate >= DateTime.UtcNow.AddMinutes(-3) & au.UserName != IM.UserName()
                              select au.UserName);

        string[] items = new string[getUsersOnline.Count()];
        int i = 0;
        foreach (string user in getUsersOnline)
        {
            items[i] = user;
            i++;
        }
        return items;
    }
    /// <summary>
    /// gets all the offline users.
    /// </summary>
    /// <returns>returns a string of offline users.</returns>
    [WebMethod]
    [System.Web.Script.Services.ScriptMethod()]
    public string[] getUsersOffline()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var getUsersOffline = (from au in db.aspnet_Users
                               where au.LastActivityDate <= DateTime.UtcNow.AddMinutes(-3) & au.UserName != IM.UserName()
                               select au.UserName);

        string[] items = new string[getUsersOffline.Count()];
        int i = 0;
        foreach (string user in getUsersOffline)
        {
            items[i] = user;
            i++;
        }
        return items;
    }
}

